﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZSZ.Model;

namespace ZSZ.DAL
{
   public partial class BaseDal<T> where T :BaseEntity
    {
        /// <summary>
        /// 多个实体数据模型切换
        /// </summary>
        public DbContext ctx
        {
            get { return DbContextFactory.GetCurrentDbContext(); }
        }


        #region 查询
        /// <summary>
        /// 获取所有没有软删除的数据
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return ctx.Set<T>().Where(e => e.IsDeleted == false);
        }

        /// <summary>
        /// 获取总数据条数
        /// </summary>
        /// <returns></returns>
        public long GetTotalCount()
        {
            return GetAll().LongCount();
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public IQueryable<T> GetPagedData(int startIndex, int count)
        {
            return GetAll().OrderBy(e => e.CreateDateTime)
                .Skip(startIndex).Take(count);
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="entities"></param>
        /// <param name="total"></param>
        /// <param name="pageIndex">默认第1页</param>
        /// <param name="pageSize">默认一页10条</param>
        /// <returns></returns>
        public IQueryable<T> GetPagedData(IQueryable<T> entities,out long total,int pageIndex,int pageSize)
        {
            total = entities.Count();
            return entities.OrderBy(e=>e.Id).Skip(pageSize*(pageIndex-1)).Take(pageSize);
        }

        /// <summary>
        /// 查找id=id的数据，如果找不到返回null
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetById(long id)
        {
            return GetAll().Where(e => e.Id == id).SingleOrDefault();
        }
        #endregion

        #region CUD
        public void MarkDeleted(long id)
        {
            var data = GetById(id);
            data.IsDeleted = true;
            // ctx.SaveChanges();
        }


        public void MarkDeleted(T entity)
        {
            entity.IsDeleted = true;
            // ctx.SaveChanges();
        }

        public void Deleted(T entity)
        {
            ctx.Entry(entity).State = EntityState.Deleted;
            // ctx.SaveChanges();
        }

        public void Add(T entity)
        {
            ctx.Set<T>().Add(entity);
            // ctx.SaveChanges();
        }
        public void Update(T entity)
        {
            ctx.Entry(entity).State = EntityState.Modified;
            // ctx.SaveChanges();
        } 
        #endregion
    }
}
